﻿using AnlianCommon.Common.Domains.ProductionManagement;
using AnlianCommon.Common.DTO;
using AnlianCommon.Common.Infrastructure.IRepository;
using AnlianCommon.Enum;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace SheepCommon.API.SheepCommands.PregnancyTestes
{
    public class PregnancyTestBackFillHandler : IRequestHandler<PregnancyTestBackFillCommand, Result>
    {
        private readonly IBaseRepository<PregnancyTest> _pregnancyTestRepository;
        private readonly IBaseRepository<SheepArchives> _archivesRepository;

        public PregnancyTestBackFillHandler(IBaseRepository<PregnancyTest> pregnancyTestRepository, IBaseRepository<SheepArchives> archivesRepository)
        {
            _pregnancyTestRepository = pregnancyTestRepository;
            _archivesRepository = archivesRepository;
        }


        /// <summary>
        /// 种母妊检反填业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(PregnancyTestBackFillCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Deleted };
            try
            {
                var pregnancyTest = await(await _pregnancyTestRepository.GetAll()).Where(c => c.PregnancyTestId == request.PregnancyTestId).FirstOrDefaultAsync();
                if (pregnancyTest != null)
                {
                    result.Data = pregnancyTest;
                    var sheepArchives = await (await _archivesRepository.GetAll()).Where(c => c.RecordAuricle == pregnancyTest.EarBugles).FirstOrDefaultAsync();
                    if(sheepArchives != null)
                    {
                        sheepArchives.IsPregnancyTest = 1;//代表妊检
                        var sheep = await _archivesRepository.Update(sheepArchives);//修改档案表是否妊检状态
                    }

                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
